package alejandro.castro.extras;

import java.util.Random;

import alejandro.castro.asteroid.AsteroidScene;
import alejandro.castro.asteroid.components.Asteroid;

public class AsteroidInstantiator extends Thread {
	
	private static final int ADD_RATE = 4000;
	private static final double PIx2 = Math.PI * 2;
	private static final int RADIO = 400;
	
	
	private AsteroidScene scene;	

	public AsteroidInstantiator(AsteroidScene scene) {
		this.scene = scene;
	}

	@Override
	public void run() {
		super.run();
		Random random = new Random();
		
		double angle;
		
		double xInit;
		double yInit;
		double xMove;
		double yMove;
		double hypotenuse;
		
		
		while(true){			
			angle = random.nextDouble() * PIx2;

			xMove =  Math.sin(angle);
			yMove = - Math.cos(angle);		
			
			//versor
			hypotenuse = Math.sqrt(xMove * xMove + yMove * yMove);
			xMove = xMove / hypotenuse;
			yMove = yMove / hypotenuse;
			
			//puntos fuera de la pantalla			
			xInit = -xMove * RADIO + getDisplayCenterX();
			yInit = -yMove * RADIO + getDisplayCenterY();
			
			try {
				this.scene.componentsAdding.acquire();
				
				this.scene.addAsteroid(new Asteroid(xInit, yInit, xMove, yMove));
				
				this.scene.componentsAdding.release();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			
			try {
				sleep(random.nextInt(ADD_RATE));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private double getDisplayCenterY() {		
		return scene.getGame().getDisplayHeight() / 2;
	}
	
	private double getDisplayCenterX() {		
		return scene.getGame().getDisplayWidth() / 2;
	}
	
	

}


